<template>
  <view class="location-detail">
    <up-toast ref="uToastRef" />
    <view class="topbar" :style="topbarStyle">
      <view class="topbar-returnBtn" @click="handleReturnPage">
        <up-icon name="arrow-left" color="white" size="24"></up-icon>
        <text class="topbar-returnBtn-text">返回</text>
      </view>
      <!-- 收藏 -->
      <view :class="item.isCollect ? 'zoomAnimationClass' : ''">
        <up-icon v-if="item.isCollect" name="star-fill" color="#feb93b" size="24" @click="handleCollect" />
        <up-icon v-else name="star" size="24" color="#fffff" @click="handleCollect" />
      </view>
    </view>
    <!-- v-if="item.imageUrlList"解决提示<swiper>: display-multiple-items 不能大于 swiper-item 数量的错误 -->
    <up-swiper v-if="item.imageUrlList" :list="item.imageUrlList" indicator height="260" indicatorStyle="bottom: 24px" @click="handlePreviewImg" />
    <!-- :style="`height: calc(100vh - ${260 + 63}px)`" -->
    <view class="main">
      <view class="main-info">
        <view class="main-info-title">{{ item.title }}</view>
        <text class="main-info-price"><text class="main-info-price-prefix">￥</text>{{ item.price }}</text>
        <up-rate v-model="item.rate" gutter="0" active-color="#feb93b" size="20" allowHalf readonly />
        <view class="main-info-desc">营业时间: {{ item.workTime }}</view>
      </view>
      <view class="main-location">
        <view class="main-location-title" @click.stop="handleDetail">
          <up-icon name="map-fill" size="18" color="#333333"></up-icon>
          {{ item.city + item.district + item.address }}
          <up-icon name="arrow-right" color="#333333" size="14" />
        </view>
        <view class="main-location-desc">距您{{ item.distance >= 1000 ? `${(item.distance / 1000).toFixed(2)}千米` : `${item.distance}米` }}</view>
        <view class="main-location-btn" @click.stop="handlePhoneCall"><up-icon name="phone-fill" size="26" color="#0154a4"></up-icon></view>
        <view class="main-location-map">
          <map enable-3D :style="fullMapStyle" :latitude="latitude" :longitude="longitude" :markers="markers" :polyline="polyline" :include-points="includePoints" />
        </view>
      </view>
      <up-gap bgColor="#f1f1f1" height="12" />
      <view class="main-intro">
        <view class="main-intro-title">站点简介</view>
        <view class="main-intro-desc">{{ item.description }}</view>
      </view>
      <up-gap bgColor="#f1f1f1" height="12" />
      <view class="main-comment">
        <view v-if="item.commentList && item.commentList.length > 0">
          <view class="main-comment-title">{{ `全部评论${item.commentList.length}` }}</view>
          <view class="main-comment-item" v-for="comment in item.commentList" :key="comment.id">
            <image class="main-comment-item-avatar" :src="comment.userAvatar" />
            <view>
              <view class="main-comment-item-user">{{ comment.userName }}</view>
              <view class="main-comment-item-time">{{ comment.createTime }}</view>
              <up-rate v-model="comment.rate" gutter="0" active-color="#feb93b" size="20" allowHalf readonly />
              <view class="main-comment-item-desc">{{ comment.content }}</view> 
            </view>
          </view>
        </view>
        <view v-else>
          <view class="main-comment-title">用户评论</view>
          <view class="main-comment-empty">暂无评论</view>
        </view>
      </view>
    </view>
	<view class="bottom-bar">
	  <button class="bottom-bar-btn" @click="handleChooseCar">立即预约</button>
	</view>
    <ycy-choose-car ref="chooseCarRef" @onConfirm="handleSubmit" />
  </view>
</template>

<script setup>
import { onLoad, onReady, onPageScroll } from '@dcloudio/uni-app';
import { getCurrentInstance, ref, computed, reactive } from 'vue';
import useMapUtils from '@/utils/map.js';
import API from '@/api';

const instance = getCurrentInstance().proxy;
const eventChannel = instance.getOpenerEventChannel();

onLoad(options => {
  if(options.carId) currentCarId.value = options.carId;
  eventChannel.on && eventChannel.on('locationItem', locationItem => {
	  console.log('eventChannel');
    item.value = locationItem
    getCollect();
    getCommentList();
	  getMapNavigate();
    // console.log('locationItem', locationItem);
  })
})

// onReady(() => {
// 	console.log('onReady');
// })

onPageScroll(e => {
  if (e.scrollTop < topbar.startScroll) topbar.scrollDistance = topbar.startScroll;
  else if (e.scrollTop > topbar.startScroll + topbar.maxScroll) topbar.scrollDistance = topbar.startScroll + topbar.maxScroll;
  else topbar.scrollDistance = e.scrollTop;
})

const { globalData } = getApp();
const topbarStyle = computed(() => {
  const colorValue = Math.round((topbar.scrollDistance - topbar.startScroll) / topbar.maxScroll * 255); // 计算颜色值
  const rgbaColor = `rgba(18, 87, 150, ${colorValue / 255})`; // 根据#125796转rgba颜色值计算添加透明度的颜色值
  return `height: ${globalData.menuBottom + 6}px; padding-right: calc(100% - ${globalData.menuLeft - 12}px); padding-top: ${globalData.statusBarHeight}px; background-color: ${rgbaColor}`
})

const { getUserLocationMarker, getRoutePlan, MapMarker, defaultLoaction, openLocation } = useMapUtils();
const topbar = reactive({
  startScroll: 173,
  maxScroll: 20,
  scrollDistance: 0
})
const currentCarId = ref();
const chooseCarRef = ref();
const uToastRef = ref();
const item = ref({});
const latitude = ref(defaultLoaction.latitude);
const longitude = ref(defaultLoaction.longitude);
const fullMapStyle = computed(() => 'width: 100%; height: 100%;')
const userMarker = computed(() => new MapMarker({ latitude: latitude.value, longitude: longitude.value }));
const markers = ref([userMarker]);
const polyline = ref([]);
const includePoints = ref([]);

const handlePreviewImg = index => {
  uni.previewImage({
    current: index,
    urls: item.value.imageUrlList
  })
}

const handlePhoneCall = () => {
		if (!item.value.tel) {
			getApp().globalData.toast.error(uToastRef.value, '该门店暂无联系方式');
			return;
		}
    uni.makePhoneCall({
      phoneNumber: item.value.tel
    });
  };

  const handleDetail = () => {
    openLocation({
      name: item.value.title,
      address: item.value.address,
      latitude: item.value.latitude,
      longitude: item.value.longitude
    })
    // getApp().globalData.toast.success(uToastRef.value, '详情页(敬请期待)');
  };

const handleCollect = async () => {
  if (item.value.isCollect) await API.collect.delete(item.value.id);
  else await API.collect.add({ id: item.value.id, title: item.value.title });
  item.value.isCollect = !item.value.isCollect;
  // getApp().globalData.toast.success(uToastRef.value, item.value.isCollect ? '收藏成功' : '取消收藏');
}

const getCollect = async () => {
  const res = await API.collect.detail(item.value.id);
  if (res.data) item.value.isCollect = true;
  else item.value.isCollect = false;
}

const getCommentList = async () => {
  const res = await API.comment.getList(item.value.id);
  item.value.commentList = res.data.map(item => ({
    id: item.id,
    userName: item.isAnonymity ? '匿名' : item.userName,
    userAvatar: item.isAnonymity ? 'https://img.ixintu.com/download/jpg/20200901/3e9ce3813b7199ea9588eeb920f41208_512_512.jpg!ys' : item.avatar,
    createTime: item.createTime,
    content: item.content,
    rate: item.rate
  })).concat([
    {
      id: '1',
      userName: '着迷',
      userAvatar: 'https://thirdqq.qlogo.cn/g?b=sdk&k=oQJibma50FXHgWCIn3R2edA&kti=ZMougwAAAAA&s=140&t=1690964846',
      content: '服务态度很好，价格便宜',
      createTime: '2024-06-04 12:51:24',
      rate: 5
    },
    {
      id: '2',
      userName: '淡写',
      userAvatar: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.HNCroQQ0lGlvJTs4ZELojwAAAA?w=215&h=215&c=7&r=0&o=5&pid=1.7',
      content: '过程很快，专业',
      createTime: '2021-05-28 08:33:12',
      rate: 4
    }
  ]);
}

const getMapNavigate = () => {
  getApp().globalData.toast.loading(uToastRef.value);
  getUserLocationMarker(
    (res, loaction) => {
      // markers.value = [res];
      // latitude.value = loaction.latitude;
      // longitude.value = loaction.longitude;
      getRoutePlan({
        from: {
          latitude: res.latitude,
          longitude: res.longitude
        },
        to: {
          latitude: item.value.latitude,
          longitude: item.value.longitude
        },
        startPointMarkerOption: {
          width: 36,
          height: 36,
          callout: null
        },
        endPointMarkerOption: {
          width: 36,
          height: 36,
          iconPath: '/static/image/location_car.png',
          callout: {
            content: item.value.title
          }
        }
      }, res => {
        markers.value = res.markers;
        polyline.value = res.polyline;
        includePoints.value = res.includePoints;
        console.log('markers', markers.value);
        console.log('includePoints', includePoints.value);
      }) //模拟
      // isOpenLocation.value = true;
      getApp().globalData.toast.closeLoading(uToastRef.value);
    },
    () => {
      getRoutePlan({
        from: {
          latitude: defaultLoaction.latitude,
          longitude: defaultLoaction.longitude
        },
        to: {
          latitude: item.value.latitude,
          longitude: item.value.longitude
        },
        startPointMarkerOption: {
          width: 36,
          height: 36,
          callout: null
        },
        endPointMarkerOption: {
          width: 36,
          height: 36,
          iconPath: '/static/image/location_car.png',
          callout: {
            content: item.value.title
          }
        }
      }, res => {
        markers.value = res.markers;
        polyline.value = res.polyline;
        includePoints.value = res.includePoints;
        console.log('markers', markers.value);
        console.log('includePoints', includePoints.value);
      }) //模拟

      getApp().globalData.toast.closeLoading(uToastRef.value);
      // isOpenLocation.value = false;
      getApp().globalData.toast.error(uToastRef.value, '请打开手机定位');
    }
  );
}

const handleChooseCar = () => {
	if (currentCarId.value && currentCarId.value !== 'undefined' && currentCarId.value !== 'null') {
    handleSubmit({ id: currentCarId.value });
  } else chooseCarRef.value.open();
}

const handleSubmit = carItem => {
	chooseCarRef.value.close();
  const stationData = {
    checkStationId: item.value.id,
    checkStation: item.value.title,
    checkStationLocation: item.value.address,
    price: item.value.price,
    tel: item.value.tel,
    latitude: item.value.latitude,
    longitude: item.value.longitude,
  }
	uni.navigateTo({
		url: `/pages/addOrder/addOrder?carId=${carItem.id}&stationData=${JSON.stringify(stationData)}`
	})
}

  const handleReturnPage = () => {
    uni.navigateBack();
  };
</script>

<style lang="scss" scoped>
.location-detail {

  .topbar {
    color: white;
    z-index: 1;
    position: fixed;
    width: 100%;
    box-sizing: border-box;
    padding: 0 12px;
    // background-color: transparent;
    // transition: background-color 0.3s ease; /* 渐变效果 */
    @include flex-row(space-between, center);

    &-returnBtn {
      @include flex-row(flex-start, center);

      &-text {
        margin-left: 4px;
        font-size: 14px;
      }
    }

    &-title {
      // font-size: 18px;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  .main {
    position: relative;
    top: -12px;
    background-color: $uni-bg-color-grey;
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
    padding-bottom: calc(18px + 45px);
    
    &-info {
      padding: 12px 0;
      margin: 0 12px;
      position: relative;
      color: $uni-text-color;
      border-bottom: 1px solid $uni-border-color-light;

      &-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 12px;
        padding-right: 92rpx;
      }

      &-desc {
        margin-top: 12px;
        font-size: 13px;
        color: $uni-text-color-deep-grey;
      }

      &-price {
        position: absolute;
        top: 12px;
        right: 0;
        font-size: 18px;
        color: $uni-color-primary;
        font-weight: bold;

        &-prefix {
          font-size: 14px;
        }
      }
    }

    &-location {
      position: relative;
      padding: 12px;
      color: $uni-text-color;

      &-title {
        display: flex;
        font-size: 15px;
        font-weight: bold;
      }

      &-desc {
        margin: 12px 0;
        margin-left: 18px;
        font-size: 13px;
        color: $uni-text-color-deep-grey;
      }

      &-map {
        border: 1px solid $uni-border-color-light;
        border-radius: 12px;
        overflow: hidden;
        @include size(100%, 180px);
      }

      &-btn {
        position: absolute;
        top: 12px;
        right: 12px;
        @include size(36px);
        @include flex-row(center, center);
        border-radius: 12px;
        background-color: #e4eef7;
      }
    }

    &-intro {
      padding: 12px;
      color: $uni-text-color;

      &-title {
        font-size: 15px;
        font-weight: bold;
      }

      &-desc {
        margin-top: 12px;
        font-size: 13px;
        color: $uni-text-color;
      }
    }

    &-comment {
      padding: 12px;
      padding-bottom: 0;

      &-title {
        font-size: 15px;
        font-weight: bold;
        margin-bottom: 12px;
      }

      &-empty {
        font-size: 14px;
        color: $uni-text-color-deep-grey;
        // @include size(100%, 80px);
        padding-bottom: 12px;
        @include flex-row(center, center);
      }

      &-item {
        display: flex;
        position: relative;
        padding: 12px 0;
        min-height: 80px;
        border-bottom: 1px solid $uni-border-color-light;

        &-avatar {
          @include size(36px);
          border-radius: 50%;
          margin-right: 12px;
        }

        &-user {
          color: $uni-text-color-deep-grey;
          font-size: 14px;
          margin-bottom: 6px;
        }

        &-time {
          position: absolute;
          right: 0;
          top: 0;
          font-size: 12px;
          color: $uni-text-color-grey;
        }

        &-desc {
          margin-top: 12px;
          font-size: 14px;
          color: $uni-text-color;
        }
      }
    }
  }
  
  .bottom-bar {
    z-index: 9;
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: $uni-bg-color-grey;
    padding: 12px;
    padding-bottom: 18px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
  
    &-btn {
      flex: 1;
      height: 45px;
      line-height: 45px;
      border-radius: 12px;
      box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.02);
      text-align: center;
      color: white;
      font-weight: lighter;
      letter-spacing: 2px;
      background: linear-gradient(145deg, #1e7eba, #0558a8);
    }
  }
}
</style>